<?php
defined('IN_CMS') or die('Direct access to Script restricted.');

class Mailer
{
	public $subject;		// (string) Тема
	public $text;			// (string) Текст сообщения (txt-вариант)
	public $html;			// (string) Текст сообщения (html-вариант)
	public $from;			// (string) От кого
	public $to;				// (string) Кому
	public $cc;				// (string) Копия
	public $bcc;			// (string) Скрытая копия
	public $charset;		// (string) Кодировка (по умолчанию utf-8)
	public $parameters;		// (array)

	private $sHeaders;		// (string)
	private $sBody;			// (string)
	private $sContentType;	// (string)
	private $sHtmlTemplate;	// (string)
	private $sBoundary;		// (string)
	private $aAttaches;		// (array)

	// Конструктор класса
	public function __construct()
	{
		$this->charset       = 'utf-8';
		$this->aAttaches     = array();
		$this->sBoundary     = '----'.substr(md5(uniqid(rand(),true)),0,16);
		$this->sHtmlTemplate = '<html><head><title>{title}</title></head><body>{body}</body></html>';
	}

	// Добавить заголовок
	public function DoHeader($sHeader)
	{
		$this->sHeaders .= $sHeader."\n\n";
	}

	// Прикрепить файл
	public function Attach($sPath,$mimeType)
	{
		/*
		MimeTypes:

		application/msword                  doc
		application/octet-stream            bin dms lha lzh exe class so dll
		application/ogg                     ogg
		application/pdf                     pdf
		application/rar                     rar
		application/x-javascript            js
		application/x-shockwave-flash       swf
		application/x-tar                   tar
		application/xml                     xml xsl
		application/zip                     zip
		audio/midi                          mid midi kar
		audio/mpeg                          mpga mp2 mp3
		audio/x-wav                         wav
		image/bmp                           bmp
		image/gif                           gif
		image/jpeg                          jpeg jpg jpe
		image/png                           png
		text/css                            css
		text/html                           html htm
		text/php                            php php3 php4 phtml
		text/plain                          asc txt
		text/rtf                            rtf
		text/xml                            xml
		video/mpeg                          mpeg mpg mpe
		video/quicktime                     qt mov
		*/
		if (file_exists($sPath))
		{
			$sName=basename($sPath);
			$sAttach ="Content-Type: $mimeType; name=\"$sName\"\n";
			$sAttach.="Content-Disposition: attachment; filename=\"$sName\"\n";
			$sAttach.="Content-Transfer-Encoding: base64\n";
			$sAttach.="Content-Location: $sName\n";
			$sAttach.="Content-ID: <".$sName.">\n";  // тогда в теле письма или шаблоне к картинкам можно будет обращаться: <img src="cid:pics_name">
			$sAttach.="\n";
			$sAttach.=base64_encode(file_get_contents($sPath))."\n";
			$this->aAttaches[] = $sAttach;
		}
	}

	// Добавить HTML
	public function AddHtml($sHtml)
	{
		$this->html .= $sHtml."\n";
	}

	// Добавить HTML
	public function AddParameters($sParameters)
	{
		$this->parameters = $sParameters;
	}

	// Установить шаблон
	public function SetTemplate($sPath)
	{
		if (file_exists($sPath)) $this->sHtmlTemplate = file_get_contents($sPath);
	}

	// Отправить
	public function Send()
	{
		//print '<hr />html:<hr />' . $this->html;
		//print '<hr />sHtmlTemplate:<hr />' . $this->sHtmlTemplate . '<hr />';

		$iCountAtt=count($this->aAttaches);
		$this->sHeaders ="From: {$this->from}\n";
		$this->sHeaders.="Reply-To: {$this->from}\n";
		$this->sHeaders.="Return-Path: {$this->from}\n";
		$this->sHeaders.="CC: {$this->cc}\n";
		$this->sHeaders.="BCC: {$this->bcc}\n";
		$this->sHeaders.="Subject: {$this->subject}\n";
		$this->sHeaders.="X-Mailer: PHPMail Tool\n";
		$this->sHeaders.="Mime-Version: 1.0\n";
		if (!$this->html && !$iCountAtt)
		{
			$this->sHeaders.='Content-Type: text/plain; charset='.$this->charset."\n";
			$this->sBody = $this->text;
		}
		elseif ($this->html && !$iCountAtt)
		{
			$this->sHeaders.='Content-Type: text/html; charset='.$this->charset."\n";
			$aFields=array();
			$aFields['{title}'] = $this->subject;
			$aFields['{body}']  = $this->html;

			$strHTML = strtr($this->sHtmlTemplate, $aFields);
			if (isset($this->parameters) && count($this->parameters) > 0)
			{
				$strHTML = strtr($strHTML, $this->parameters);
			}
			$this->sBody = $strHTML; // . "\n";
			//$this->sBody = strtr($this->sHtmlTemplate,$aFields);
		}
		elseif (!$this->html && $iCountAtt)
		{
			$this->sHeaders.="Content-Type: multipart/mixed; boundary=\"{$this->sBoundary}\"\n";
			foreach ($this->aAttaches as $sAttach)
			{
				$this->sBody .= "--{$this->sBoundary}\n";
				$this->sBody .= $sAttach;
			}
			$this->sBody .= "--{$this->sBoundary}--\n";
		}
		elseif ($this->html && $iCountAtt)
		{
			//$this->sHeaders.="Content-Type: multipart/mixed; boundary=\"{$this->sBoundary}\"\n";
			$this->sHeaders.="Content-Type: multipart/related; boundary=\"{$this->sBoundary}\"\n";  // тогда файлы не будут отображаться как приложения

			$this->sBody .= "--{$this->sBoundary}\n";
			$this->sBody .= "Content-Type: text/html; charset={$this->charset}\n";
			$this->sBody .= "Content-Transfer-Encoding: 8bit\n";
			$this->sBody .= "\n";
			$aFields=array();
			$aFields['{title}'] = $this->subject;
			$aFields['{body}']  = $this->html;

			$strHTML = strtr($this->sHtmlTemplate, $aFields);
			if (isset($this->parameters) && count($this->parameters) > 0)
			{
				$strHTML = strtr($strHTML, $this->parameters);
			}
			$this->sBody .= $strHTML . "\n";

			foreach ($this->aAttaches as $sAttach)
			{
				$this->sBody .= "--{$this->sBoundary}\n";
				$this->sBody .= $sAttach . "\n"; // ."\n";
			}
			$this->sBody .= "--{$this->sBoundary}--\n";
		}
		@mail($this->to, $this->subject, $this->sBody, $this->sHeaders);
	}

}
?>